package com.easylinkin.linkappapi.alarm.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.alarm.dto.AiRule;
import com.easylinkin.linkappapi.alarm.entity.AiAlarmCount;
import com.easylinkin.linkappapi.alarm.service.AiAlarmCountService;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.deviceattributestatus.entity.DeviceAttributeStatus;
import com.easylinkin.linkappapi.deviceattributestatus.service.DeviceAttributeStatusService;
import com.easylinkin.linkappapi.elasticsearch.entity.AiCameraVo;
import com.easylinkin.linkappapi.elasticsearch.service.IEService;
import com.easylinkin.linkappapi.elasticsearch.service.impl.EsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: ai相机预警统计管理
 */
@RestController
@RequestMapping("aiAlarmCount")
@Api(tags = "ai相机预警统计管理")
public class AiAlarmCountController {
  
  @Autowired
  private AiAlarmCountService aiAlarmCountService;
  @Resource
  private DeviceAttributeStatusService service;
  @Autowired
  private DeviceService deviceService;
  @Autowired
  private IEService esService;

  /**
   * @Description: 增加ai相机预警统计
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加ai相机预警统计")
  public RestMessage insert(@RequestBody AiAlarmCount aiAlarmCount){
    //todo 参数验证
    aiAlarmCountService.insert(aiAlarmCount);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑ai相机预警统计
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑ai相机预警统计")
  public RestMessage updateById(@RequestBody AiAlarmCount aiAlarmCount){
    Assert.notNull(aiAlarmCount.getId(),"id不能为空");
    aiAlarmCountService.updateOne(aiAlarmCount);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询ai相机预警统计详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询ai相机预警统计详情")
  public RestMessage findById(@PathVariable("id")Long id) {
    Assert.notNull(id,"id不能为空");
    AiAlarmCount aiAlarmCount = aiAlarmCountService.getById(id);
    return RestBuilders.successBuilder().data(aiAlarmCount).build();
  }

  /**
   * 大屏预警统计
   */
  @GetMapping("count")
  @ApiOperation("大屏预警统计")
  public RestMessage count() {
//    Map<String,Object> map = aiAlarmCountService.countNum();
//    从es取 20221017
    RequestModel<AiCameraVo> aiCameraVo = new RequestModel<>();
    Page page = new Page();
    page.setCurrent(1);
    page.setSize(1);
    AiCameraVo cameraVo = new AiCameraVo();
    aiCameraVo.setPage(page);
    List<AiRule> list = AiRule.getDefaultList();
    list.forEach(l->{
      if (l.getName().contains("安全帽")){
        cameraVo.setRuleName("未佩戴安全帽");
      }else if (l.getName().contains("反光衣")){
        cameraVo.setRuleName("未穿戴反光衣");
      }else {
        cameraVo.setRuleName(l.getName());
      }
      //设置当天开始和结束时间
      cameraVo.setQueryTimeStart(DateUtil.formatDateTime(DateUtil.beginOfDay(new Date())));
      cameraVo.setQueryTimeEnd(DateUtil.formatDateTime(DateUtil.endOfDay(new Date())));
      aiCameraVo.setCustomQueryParams(cameraVo);
      IPage<AiCameraVo> aiCamera = esService.queryAiCamera(aiCameraVo);
      l.setNum((int) aiCamera.getTotal());
    });
    Map<String,Object> map =  new HashMap<>();
//    cameraVo.setRuleName(null);
//    aiCameraVo.setCustomQueryParams(cameraVo);
//    IPage<AiCameraVo> aiCamera = esService.queryAiCamera(aiCameraVo);
    map.put("sum",list.stream().mapToDouble(l->l.getNum()).sum());
    map.put("data",list);
    return RestBuilders.successBuilder().data(map).build();
  }

  /**
   * ai相机预警详情
   */
  @ApiOperation("设备属性历史数据流水查询")
  @PostMapping("getHistoricDataPageFromEs")
  public RestMessage getHistoricDataPageFromEs(@RequestBody RequestModel<DeviceAttributeStatus> requestModel) {
    Assert.notNull(requestModel, "参数为空");
    Assert.notNull(requestModel.getPage(), "分页参数为空");
    Assert.notNull(requestModel.getCustomQueryParams(), "参数不完整");
    IPage<Map> dataFromEs = service.getHistoricDataFromEs(requestModel);
    //        子设备code
    List<String> deviceCodes = dataFromEs.getRecords().stream().map(r -> (String)r.get("ChnName"))
        .collect(Collectors.toList());
    if (!deviceCodes.isEmpty()) {
      LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
      lambdaQueryWrapper.select(Device::getCode, Device::getName);
      lambdaQueryWrapper.in(Device::getCode, deviceCodes);
      List<Device> devices = deviceService.list(lambdaQueryWrapper);
      if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(devices)) {
        dataFromEs.getRecords().forEach(r->{
          List<Device> chnNames = devices.stream()
              .filter(d -> d.getCode().equals(r.get("ChnName")))
              .collect(Collectors.toList());
          if (chnNames.size()>0){
            r.put("deviceName",chnNames.get(0).getName());
          }
        });
      }
    }
    return RestBuilders.successBuilder().data(dataFromEs).build();
  }
}

